<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>选择角色</title>
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="stylesheet" href="/layui/css/layui.css" media="all">
</head>
<body>
<div style="margin: 20px" id="roleTree"></div>
<form class="layui-form">
  <label for="id"></label>
  <input id="id" name="id" class="layui-hide" />
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button id="insert" class="layui-btn" lay-submit lay-filter="submit">提交</button>
      <button id="update" class="layui-btn" lay-submit lay-filter="cancel">取消</button>
    </div>
  </div>
</form>
<script src="/layui/layui.js" charset="utf-8"></script>
<script src="/jquery/jquery-3.5.1.min.js"></script>
<script>
  $.ajaxSetup({
    dataType: "json",
    contentType: "application/json",
  });
  layui.use(['tree', 'form'], function () {
    const tree = layui.tree;
    const form = layui.form;

    const roleTree = tree.render({
      id: 'roleTree',
      elem: '#roleTree',  //绑定元素
      showCheckbox: true,
      onlyIconControl: true,
    });

    form.on("submit(submit)", function (data){
      const userId = Number(data.field.id);
      const roleIds = getCheckedIds(roleTree.getChecked());
      const request = JSON.stringify({"userId": userId, "roleIds": roleIds });
      $.ajax({
        url: "/api/user/role",
        method: 'post',
        data: request,
        success: function (data) {
          if (data.code === 200) {
            layer.msg('修改成功')
            setTimeout(function () {
              const index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
              parent.layer.close(index); //再执行关闭
            }, 1500);
          } else {
            layer.msg(data.message);
          }
        }
      });
      return false;
    })

    form.on("submit(cancel)", function () {
      const index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
      parent.layer.close(index); //再执行关闭
      return false;
    })

    $.get("/api/role/list", function (response) {
      if (response.code === 200){
        const data = toTreeJson(response.data)
        roleTree.reload({data: data});
        // 菜单树加载之后，在处理添加check的节点
        const id = $("#id").val();
        $.get("/api/user/role/"+id, function (response){
          if (response.code === 200){
            roleTree.setChecked(response.data.roleIds);
          }
        });
      }
    });
  });

  // 转换为layui使用的树结构
  function toTreeJson(data){
    const tarData = [];
    for (let i = 0; i < data.length; i++) {
      const item = {"id":data[i].id, "title": data[i].name, "disabled":data[i].state === 'off', "type": data[i].type};
      tarData.push(item);
    }
    return tarData;
  }
  // 获取选中节点ids
  function getCheckedIds(data){
    let ids = [];
    for (let i = 0; i < data.length; i++) {
      const id = data[i].id;
      ids.push(id);
    }
    return ids;
  }
</script>
</body>
</html>